<template>
  <div class="call-label" id="callTable">
    <div id="call_cont" style="padding: 20px 20px 40px">
      <div class="operate-div">
        <div class="left">
          <span @click.stop="add" class="add"
            ><i class="el-icon-plus"></i
            >{{ $t("public.add") }}</span
          >
          <span
            @click.stop="refresh"
            style="padding-right: 10px; cursor: pointer"
            ><i class="iconfont icon-shuaxin"></i
            >{{ $t("public.refresh") }}</span
          >
        </div>
        <el-input
          :placeholder="$t('configLazyLoad.channel.phoneBookTips2')"
          class="condition right"
          v-model.trim="searchContent"
          size="mini"
          @keyup.native.enter="handleIconClick"
        >
          <i
            class="el-input__icon el-icon-search"
            slot="suffix"
            @click="handleIconClick"
          >
          </i>
        </el-input>
      </div>
      <div class="phonePage">
       <Pagination
        class="page"
        :small="true"
        :currentPage="pagination.currentPage"
        :count="pagination.count"
        :pageSize="pagination.pageSize"
        @turnPage="turnPage"
        :totalPage="Math.ceil(pagination.count/pagination.pageSize)"
      >
      </Pagination>
      </div>
       <el-table :data="currentTable" style="width: 100%" size="mini">
        <el-table-column :label="$t('configLazyLoad.qualityCheck.name')" align="center">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('customer.customerSlot.tel')" align="center">
           <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.number }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('monitor.operate')" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleEdit(scope.row)">{{$t('public.edit2')}}</el-button>
            <el-button type="text" size="mini" class="del" @click="handleDelete(scope.row)">{{$t('public.delete')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog :title="title" :visible.sync="dialogTableVisible" width="30%" @close='formClose'>
       <el-form label-width="50px" :model="form" ref="form" :rules="formRules">
            <el-form-item :label="$t('configLazyLoad.qualityCheck.name')" prop="name">
                <el-input v-model.trim="form.name" maxlength="50"></el-input>
            </el-form-item>
            <el-form-item :label="$t('customer.customerSlot.tel')" prop="number">
                <el-input v-model.trim="form.number" maxlength="50"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button size="mini"  @click="cancel">{{$t('public.cancel')}}</el-button>
                <el-button type="primary" size="mini" @click="submitForm('form')">{{$t('public.save')}}</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/public-modules/card/Pagination'
import { deepClone } from '@/utils/m7Utils';
export default {
  name: "phoneBook",
  data() {
    return {
      tableData: [],//全部数据
      phoneBookTable:[],//展示的数据
      currentTable:[],//分页展示数据
      title:this.$t('public.add'),
      dialogTableVisible:false,
      searchContent: "",
      baseForm:{
        name:null,
        number:null
      },
      form:{
        name:null,
        number:null
      },
      showBread:'addPhoneData',
      formRules: {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' },
        ],
        number: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
      },
      pagination: {
        pageSize: 10,
        count: 0,
        currentPage: 1
      }
    };
  },
  methods: {
    //添加
    add() {
      this.dialogTableVisible = true
      this.showBread = 'addPhoneData'
      this.title = this.$t('public.add')
    },
    //刷新
    refresh() {
      this.searchContent = "";
      this.fetchData();
    },
    //获取数据
    fetchData(isTrue) {
      this.$store.dispatch('queryCallBook', {}).then((resp) => {
        if (resp && resp.success) {
          this.tableData = resp.list || []
        }
        this.search()
        this.pagination.count = this.phoneBookTable.length
        // // 最大页数
        let maxPage = Math.ceil(this.pagination.count / this.pagination.pageSize)
        if (this.pagination.currentPage > maxPage) {
          this.pagination.currentPage = maxPage
        }
        let search = this.pagination.currentPage
        if(isTrue){
          search = 1
        }
        this.turnPage(search)
      })
    },
    handleIconClick(){
      this.fetchData()
    },
    //查询
    search(){
      let _search = this.searchContent.toLowerCase()
      this.phoneBookTable = this.tableData.filter((item) => {
        if (item.name.toLowerCase().indexOf(_search) !== -1 || item.number.toLowerCase().indexOf(_search) !== -1) {
          return true
        }
      })
    },
    //编辑
    handleEdit(row){
      this.dialogTableVisible = true
      this.showBread = 'editPhoneData'
      this.title = this.$t('public.edit2')
      this.form = deepClone(row)
    },
    //删除
    handleDelete(row){
      this.$confirm(this.$t('configLazyLoad.channel.phoneBookTips'), this.$t('public.tip'), {
      confirmButtonText: this.$t('public.confirm'),
      cancelButtonText: this.$t('public.cancel'),
      type: 'warning'
      }).then(() => {
        this.$store.dispatch('deleteCallBook', {_id:row._id}).then((resp) => {
          if (resp.success) {
            this.$message.success(this.$t('config.agent.successDel'))
          }else{
            this.$message.error(this.$t('sms.failDel'))
          }
          this.fetchData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('config.agent.cancelDel')
        });          
      });
    },
    //提交
    submitForm(form){
        this.$refs[form].validate((valid) => {
          if (valid) {
            this.dialogTableVisible = false
            if(this.form&&this.showBread!=='addPhoneData'){
              let data = {}
              data._id = this.form._id
              data.name = this.form.name
              data.number = this.form.number
              this.$store.dispatch('updateCallBook', data).then((resp) => {
                if (resp.success) {
                  this.$message.success(this.$t('userInfo.editSuccess'))
                  this.fetchData(true)
                }else{
                  this.$message.success(this.$t('userInfo.editFail'))
                }
              })
            }else{
              this.$store.dispatch('addCallBook', this.form).then((resp) => {
                if (resp.success) {
                  this.$message.success(this.$t('config.customer.addSucc'))
                  this.fetchData(true)
                }else{
                  this.$message.success(this.$t('call.addLabelFail'))
                }
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
    },
    cancel(){
      this.dialogTableVisible = false
    },
    //弹窗关闭重置表单及表单验证
    formClose(){
      this.form = deepClone(this.baseForm)
      this.$refs['form'].resetFields()
    },
    turnPage(val){
      this.pagination.currentPage = val || 1
      let size = this.pagination.pageSize || 10
      let end = Math.min(size * (val), this.pagination.count)
      this.currentTable = this.phoneBookTable.slice(size * (val - 1), end)
    }
  },
  components: {
    Pagination
  },
  beforeMount() {
    this.fetchData(true)
  },
};
</script>
<style lang="stylus" scoped>
@import "../../../../../assets/common.styl"
.state
  margin-left: 20px
.call-label
  overflow-y: auto
  height: calc(100vh - 173px)
  .title
    color $c-prompt
    height 30px
    line-height 30px
    padding 3px 10px
    overflow hidden
    text-overflow ellipsis
    max-width 100%
    white-space nowrap
    cursor pointer
  .operate-div
    display flex
    align-items center
    height 30px
    padding 10px 10px 5px
    border 1px solid #E7E7EB
    border-bottom none
    .left
      /*float left*/
      /*padding-top 5px*/
      .add
        padding-right 10px
        cursor pointer
    .right
      width 200px
      /*float left*/
      margin-left 20px
    .el-icon-plus,.icon-shuaxin,.icon-daoru,.icon-daochu1
      color $c-main
      font-size 14px
      margin-right 2px
  .pull-right
    float right
  .btn-wrap
    padding-bottom 10px
    overflow hidden
    .temp-download
      float left
      a
       color #fff
    .temp-upload
     float left
     display inline-block
     margin-left 20px
    .temp-upload-btn
      font-size 12px
      padding 8px 15px
  .el-table 
    .cell >.el-button--text.del
      color $c-pink
      cursor pointer
  .phonePage
    width 100%
    border-left 1px solid #e7e7eb
    border-right 1px solid #e7e7eb
    overflow hidden
    box-sizing border-box
  .page
    float right
</style>
